/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.oszero.deliver.server.client.sms.impl;

import com.alibaba.fastjson.JSON;
import com.oszero.deliver.server.client.sms.SmsClient;
import com.oszero.deliver.server.client.sms.dtos.SmsSendRequest;
import com.oszero.deliver.server.exception.MessageException;
import com.oszero.deliver.server.model.app.sms.HnSmsApp;
import com.oszero.deliver.server.model.app.sms.SmsApp;
import com.oszero.deliver.server.model.dto.common.SendTaskDto;
import com.oszero.deliver.server.util.MessageLinkTraceUtils;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;

/**
 * 汉脑短信服务
 */
@Service
public class HnSmsClient implements SmsClient
{
    @Override
    public void sendSms(SmsApp smsApp, SendTaskDto sendTaskDto)
    {
        try {
            HnSmsApp HnSmsApp = (HnSmsApp) smsApp;

            Map<String, Object> paramMap = sendTaskDto.getParamMap();
            String content = paramMap.get("content").toString();
            String paramSign = paramMap.containsKey("sign") ? paramMap.get("sign").toString():HnSmsApp.getSign();

            if(content.isEmpty())
                throw new Exception("短信内容为空" + JSON.toJSON(sendTaskDto));

            String msg = paramSign + content;
            List<String> users = sendTaskDto.getUsers();

            for (String phone:users)
            {
                String report= "true"; //状态报告
                SmsSendRequest smsSingleRequest = new SmsSendRequest(HnSmsApp.getAccount(), HnSmsApp.getPassword(), msg, phone,report);
                String requestJson = JSON.toJSONString(smsSingleRequest);
                String response = sendSmsByPost(HnSmsApp.getSmsSingleRequestServerUrl(), requestJson);
            }
        } catch (Exception e) {
            throw new MessageException(sendTaskDto, "HN短信服务发送失败，" + e.getMessage());
        }
        MessageLinkTraceUtils.recordMessageLifecycleInfoLog(sendTaskDto, "HN短信服务发送成功");
    }
    /**
     * 短信发送
     * @param path
     * @param postContent
     * @return
     */
    public static String sendSmsByPost(String path, String postContent) {
        URL url = null;
        try {
            url = new URL(path);
            HttpURLConnection httpURLConnection = getHttpURLConnection(url);
            OutputStream os=httpURLConnection.getOutputStream();
            os.write(postContent.getBytes("UTF-8"));
            os.flush();

            StringBuilder sb = new StringBuilder();
            int httpRspCode = httpURLConnection.getResponseCode();
            if (httpRspCode == HttpURLConnection.HTTP_OK) {
                // 开始获取数据
                BufferedReader br = new BufferedReader(
                        new InputStreamReader(httpURLConnection.getInputStream(), "utf-8"));
                String line = null;
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                }
                br.close();
                return sb.toString();

            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static HttpURLConnection getHttpURLConnection(URL url) throws IOException {
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.setRequestMethod("POST");// 提交模式
        httpURLConnection.setConnectTimeout(10000);//连接超时 单位毫秒
        httpURLConnection.setReadTimeout(10000);//读取超时 单位毫秒

        // 发送POST请求必须设置如下两行
        httpURLConnection.setDoOutput(true);
        httpURLConnection.setDoInput(true);
        httpURLConnection.setRequestProperty("Charset", "UTF-8");
        httpURLConnection.setRequestProperty("Content-Type", "application/json");

        httpURLConnection.connect();
        return httpURLConnection;
    }

}
